package com.sqx.modules.cityInfo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mchange.v1.identicator.IdList;
import com.sqx.modules.agentUserMoney.entity.AgentUserMoney;
import com.sqx.modules.agentUserMoney.service.AgentUserMoneyService;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.cityInfo.entity.CityInfo;
import com.sqx.modules.cityInfo.dao.CityInfoDao;
import com.sqx.modules.cityInfo.service.CityInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.modules.cityInfo.vo.CityInfoVo;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.sys.service.SysUserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sqx.common.utils.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 城市 服务实现类
 * @author wuChang
 * @since 2024-01-23
 */
@Service
public class CityInfoServiceImp extends ServiceImpl<CityInfoDao, CityInfo> implements CityInfoService {
    @Autowired
    private UserService userService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private AgentUserMoneyService agentUserMoneyService;

    @Override
    public Result saveCityInfo(CityInfo cityInfo) {
        if (cityInfo.getId() != null) {
            return Result.upStatus(baseMapper.updateById(cityInfo));
        } else {
            return Result.upStatus(baseMapper.insert(cityInfo));
        }
    }

    @Override
    public IPage<CityInfo> getCityInfoList(Integer page, Integer limit, CityInfo cityInfo) {
        Page<CityInfo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.selectPage(pages, new QueryWrapper<>(cityInfo).orderByAsc("sort"));
    }

    /**
     * 判断当前城市是否已开启
     * @param cityName 城市名称
     * @return true:已已开启 false 未开启
     */
    @Override
    public boolean isOpenCity(String cityName) {
        Integer count = baseMapper.selectCount(new QueryWrapper<CityInfo>().eq("city_name", cityName).eq("is_enable", 2));
        return count > 0;
    }

    @Override
    public Result updateEnable(Long id) {
        CityInfo cityInfo = baseMapper.selectById(id);
        if (cityInfo == null) {
            return Result.error("所选城市不存在");
        }
        if (cityInfo.getIsEnable() == 1) {
            cityInfo.setIsEnable(2);
        } else {
            cityInfo.setIsEnable(1);
        }
        //改上级
        CityInfo parentInfo = baseMapper.selectOne(new QueryWrapper<CityInfo>().eq("id", cityInfo.getParentId()));
        updateParentEnableCity(parentInfo, cityInfo.getIsEnable(), cityInfo.getId());
        //改下级
        List<CityInfo> childrenInfoList = baseMapper.selectList(new QueryWrapper<CityInfo>().eq("parent_id", cityInfo.getId()));
        updateChildrenEnableCity(childrenInfoList, cityInfo.getIsEnable());

        return Result.upStatus(baseMapper.updateById(cityInfo));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result setAgentCity(Long id, Long userId) {
        CityInfo info = baseMapper.selectById(id);
        if (info == null) {
            return Result.error("所选城市不存在");
        }
        if (userId != null) {
            SysUserEntity sysUserEntity = sysUserService.getById(userId);
            if (sysUserEntity == null) {
                return Result.error("所选用户不存在");
            }
            Integer count = baseMapper.selectCount(new QueryWrapper<CityInfo>().eq("agent_user_id", userId));
            if (count > 0) {
                return Result.error("当前用户已有代理城市");
            }
            if (info.getParentId() != 0 && info.getHasChildren() == 2) {
                info.setAgentUserId(userId);
                info.setAgentTime(LocalDateTime.now());
                return Result.upStatus(baseMapper.updateById(info));
            } else {
                return Result.error("仅支持设置到市");
            }
        } else {
            info.setAgentUserId(null);
            return Result.upStatus(baseMapper.updateById(info));
        }


    }

    @Override
    public Result updateCityRate(CityInfo cityInfo) {
//        SysUserEntity sysUserEntity = sysUserService.getById(cityInfo.getAgentUserId());
//        if (sysUserEntity == null) {
//            return Result.error("账号信息失效,请重新登录");
//        }
//        if (sysUserEntity.getStatus() != 1) {
//            return Result.error("账号已被禁用");
//        }
//        CityInfo city = baseMapper.selectOne(new QueryWrapper<CityInfo>().eq("agent_user_id", sysUserEntity.getUserId()));
//        if (city == null) {
//            return Result.error("你未代理任何城市");
//        }
//        if (city.getAgentUserId().equals(sysUserEntity.getUserId())) {
//            if (city.getIsEnable() != 2) {
//                return Result.error("所选市暂未开启服务,请联系管理员");
//            }
//        } else {
//            return Result.error("无权修改未代理的城市");
//        }
        CityInfo city = baseMapper.selectById(cityInfo.getId());
        city.setBaseMoney(cityInfo.getBaseMoney());
        city.setBaseKilometres(cityInfo.getBaseKilometres());
        city.setUnitOverMoney(cityInfo.getUnitOverMoney());
        city.setNightMoney(cityInfo.getNightMoney());
        city.setEarlyMoney(cityInfo.getEarlyMoney());
        city.setMinuteMoney(cityInfo.getMinuteMoney());
        city.setRiderRate(cityInfo.getRiderRate());
        city.setWaitMinuteMoney(cityInfo.getWaitMinuteMoney());
        city.setFreeWaitTime(cityInfo.getFreeWaitTime());
        if (cityInfo.getIsCover() == 1) {
            userService.updateRateByCity(city.getCityName(), cityInfo.getRiderRate());
        }
        return Result.upStatus(baseMapper.updateById(city));

    }

    @Override
    public IPage<CityInfoVo> getHasAgentCityList(Integer page, Integer limit, CityInfoVo cityInfoVo) {
        Page<CityInfoVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getHasAgentCityList(pages,cityInfoVo);
    }


    public void updateChildrenEnableCity(List<CityInfo> cityInfoList, Integer isEnable) {
        if (!cityInfoList.isEmpty()) {
            for (CityInfo info : cityInfoList) {
                info.setIsEnable(isEnable);
                baseMapper.updateById(info);
                List<CityInfo> childrenList = baseMapper.selectList(new QueryWrapper<CityInfo>().eq("parent_id", info.getId()));
                if (!childrenList.isEmpty()) {
                    updateChildrenEnableCity(childrenList, isEnable);
                }
            }
        }
    }

    /**
     *判断上级节点是否开启或关闭
     * @param cityInfo 上级节点
     * @param isEnable 开启或关闭 1关闭 2开启
     * @param id 要排除的id
     */
    public void updateParentEnableCity(CityInfo cityInfo, Integer isEnable, Long id) {
        if (cityInfo != null) {
            if (isEnable == 2) {
                //开启上级节点只需要有一个节点开启
                cityInfo.setIsEnable(isEnable);
                baseMapper.updateById(cityInfo);
                CityInfo info = baseMapper.selectOne(new QueryWrapper<CityInfo>().eq("id", cityInfo.getParentId()));
                updateParentEnableCity(info, cityInfo.getIsEnable(), cityInfo.getId());
            } else {
                //关闭上级节点的前提是 所有下级都关闭
                List<CityInfo> cityInfoList = baseMapper.selectList(new QueryWrapper<CityInfo>().eq("parent_id", cityInfo.getId()).ne("id", id));
                //判断当前父节点的子节点状态是否全部一样
                if (isAllEnable(cityInfoList, isEnable)) {
                    cityInfo.setIsEnable(isEnable);
                    baseMapper.updateById(cityInfo);
                    //获取当前节点的上级
                    CityInfo info = baseMapper.selectOne(new QueryWrapper<CityInfo>().eq("id", cityInfo.getParentId()));
                    updateParentEnableCity(info, cityInfo.getIsEnable(), cityInfo.getId());
                }
            }
        }
    }

    public boolean isAllEnable(List<CityInfo> cityInfoList, Integer isEnable) {
        //如果子类为空则表示上级已没有其他下级了。所以可以修改上级状态
        if (!cityInfoList.isEmpty()) {
            for (CityInfo info : cityInfoList) {
                if (!info.getIsEnable().equals(isEnable)) {
                    return false;
                }
            }
        }
        return true;


    }
}
